package ecode

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// Error 错误处理的结构体
type Error struct {
	StatusCode int    `json:"-"`
	Code       int    `json:"code"`
	Message    string `json:"message"`
}

// Common code
var (
	Success     = New(http.StatusOK, 0, "success")
	ServerError = New(http.StatusInternalServerError, 200500, "系统异常，请稍后重试!")
	NotFound    = New(http.StatusNotFound, 200404, http.StatusText(http.StatusNotFound))
)

func (e *Error) Error() string {
	return e.Message
}

// New 新建错误
func New(statusCode, Code int, msg string) *Error {
	return &Error{
		StatusCode: statusCode,
		Code:       Code,
		Message:    msg,
	}
}

// NewBadRequest .
func NewBadRequest(err error) *Error {
	return &Error{
		StatusCode: http.StatusBadRequest,
		Code:       200400,
		Message:    err.Error(),
	}
}

// NewNotFound .
func NewNotFound(err error) *Error {
	return &Error{
		StatusCode: http.StatusNotFound,
		Code:       200400,
		Message:    err.Error(),
	}
}

// HandleNotFound 404处理
func HandleNotFound(c *gin.Context) {
	err := NotFound
	c.JSON(err.StatusCode, err)
	return
}
